<?php
// +----------------------------------------------------------------------
// | Author: 发仔 <i@fazi.me> 
// +----------------------------------------------------------------------

namespace app\unit\controller;

use app\api\model\Company;
use think\Db;
use Wechat;
use think\session;
use think\Loader;

class Finance extends Base
{

    public function index() {


//        $company_return = Db::name('company')->where('company_id',$this->company_id)->find();
//        $quota = $company_return['quota'];
//        $unit_quota = $company_return['unit_quota'];

        $data = (new Company())->getUseMoneyByCompany($this->company_id);

        $unit_quota = sprintf('%01.2f', $data['unit_quota'] - $data['company_money']);
        $quota = sprintf('%01.2f', $data['quota'] - $data['office_money']);

        $this->assign('unit_quota',$unit_quota);
        $this->assign('quota',$quota);

        return $this->out();
    }

    //创建微信二维码
    public function wxpay() {

        $P = input('param.');
        if($P['number'] < 0.01){
            return '最小金额为0.01';
        }
        if($P['number'] == 0){
            return '不能为零';
        }
        else {
            $number = $P['number'] * 100;

            ini_set('date.timezone', 'Asia/Shanghai');

            $data = array(
                'recharge_no' => $this->_makeOrderNo(),
                "company_id" => session('company_id'),
                "number" => $P['number'],
                "date" => date("Y-m-d H:i:s"),
                "type" => '1',
                "state" => '1',
            );
            Db::name('company_recharge')->insert($data);
            $company_recharge_return = Db::name('company_recharge')->getLastInsID();

            Session::set('company_recharge_id', $company_recharge_return);

            $notify = new NativePay();
            $input = new \Wechat\WxPayUnifiedOrder();
            $input->SetBody("晋江出行充值");
            $input->SetAttach("$company_recharge_return");
            $input->SetOut_trade_no(\Wechat\WxPayConfig::MCHID . date("YmdHis"));
            $input->SetTotal_fee("$number");
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetGoods_tag("test");
            $input->SetNotify_url("http://test.jjcxfw.com/api/Notify/check_wxpay");
            $input->SetTrade_type("NATIVE");
            $input->SetProduct_id("123456789");
            $result = $notify->GetPayUrl($input);
            $url = $result["code_url"];

            $out_trade_no = $input->GetOut_trade_no();
            Session::set('out_trade_no', $out_trade_no);

            return '<img alt="模式二扫码支付" src="http://paysdk.weixin.qq.com/qrcode.php?data=' . $url . '" style="width:150px;height:150px;"/>';
        }
    }

    //预充值
    public function yuchongzhi() {

        $P = input('param.');
        $money = $P['number'];
        if(!is_numeric($money)){
            return $this->error('充值金额错误');
        }
        $money = $money + 0;

        if($money) {
            $data = array(
                'recharge_no' => $this->_makeOrderNo(),
                "company_id" => session('company_id'),
                "number" => $money,
                "date" => date("Y-m-d H:i:s"),
                "type" => '2',
                "state" => '1',
            );
            Db::name('company_recharge')->insert($data);
            return $this->success('申请成功', '/unit/finance');
        }
        else{
            return $this->error('充值金额不能为0');
        }
    }

    //充值记录
    public function topup_list() {

        $list = Db::name('company_recharge')->where('company_id',session('company_id'))->order('date desc')->select();
        $company_return = Db::name('company')->where('company_id',session('company_id'))->select();

        if($list) {
            if (!empty($list)) {
                foreach ($list as $key => $val) {
                    $list[$key]['company_name'] = $company_return[0]['company_name'];
                }
            }
        }

        $data = array(
            'code' => 1,
            'msg'  => 'ok',
            'time' => time(),
            'data' => $list
        );

        return json($data);
    }

    //给ajax查询支付结果
    public function check_for_ajax() {

        $input = new \Wechat\WxPayUnifiedOrder();
        $input->SetOut_trade_no(session('out_trade_no')); // 设置好要查询的订单
        $order = \Wechat\WxPayApi::orderQuery($input); // 进行查询
        if($order['trade_state'] == 'SUCCESS'){
            $company_recharge_return = Db::name('company_recharge')->where('company_recharge_id', $order['attach'])->find();
            if($company_recharge_return['state'] == '1'){
                $company_return = Db::name('company')->where('company_id', $company_recharge_return['company_id'])->find();
                $order['total_fee'] /= 100;
                $company_return['unit_quota'] += $order['total_fee'];
                Db::name('company')->where('company_id', $company_recharge_return['company_id'])->update(['unit_quota' => $company_return['unit_quota']]);
            }
            Db::name('company_recharge')->where('company_recharge_id', $order['attach'])->update(['state' => '3']);
            $data['state'] = 'success';
            return $data;
        }
        print_r($order); // 打印出订单信息

//        $stringA = "appid=wx53f7d66939e576d6&mch_id=1485832972&nonce_str=ec2316275641faa3aacf3cc599e8730f&out_trade_no=".session('out_trade_no');
//        $stringSignTemp = $stringA."&key=wx53f7d66939e576d6pccxpaydidigo8"; //注：key为商户平台设置的密钥key
//
//        $sign = strtoupper (MD5($stringSignTemp)); //注：MD5签名方式
//
//        $xml_data = '<xml>
//                   <appid>wx53f7d66939e576d6</appid>
//                   <mch_id>1485832972</mch_id>
//                   <nonce_str>ec2316275641faa3aacf3cc599e8730f</nonce_str>
//                   <out_trade_no>'.session('out_trade_no').'</out_trade_no>
//                   <sign>'.$sign.'</sign>
//                </xml>';//发送的xml
//        $url = 'https://api.mch.weixin.qq.com/pay/orderquery';//接收XML地址
//
//        $header[] = "Content-type: text/xml";//定义content-type为xml
//        $ch = curl_init(); //初始化curl
//        curl_setopt($ch, CURLOPT_URL, $url);//设置链接
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置是否返回信息
//        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//设置HTTP头
//        curl_setopt($ch, CURLOPT_POST, 1);//设置为POST方式
//        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);//POST数据
////        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//        $response = curl_exec($ch);//接收返回信息
//        if(curl_errno($ch)){//出错则显示错误信息
//            print curl_error($ch);
//        }
//        curl_close($ch); //关闭curl链接

//        $company_recharge_return = Db::name('company_recharge')->where('company_recharge_id',session('company_recharge_id'))->find();
//        if($company_recharge_return){
//            if($company_recharge_return['state'] == '3'){
//                $data['msg'] = 'success';
//                return $data;
//            }
//        }
//        echo session('out_trade_no');
//        print_r($company_recharge_return);
    }

    /**
     * 生成订单号
     * @author LRChang
     * @return void
     */
    private function _makeOrderNo(){
        $yearCode = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N'];
        $orderSn = $yearCode[intval(date('Y')) - 2018] . strtoupper(dechex(date('m')))
            . date('d') . substr(time(), -5) . substr(microtime(), 2, 5)
            . sprintf('%02d',rand(0,99));
        return $orderSn;
    }
}

class NativePay
{
    public function GetPayUrl($input)
    {
        Loader::import('Wechat\WxPay_Api', EXTEND_PATH);
        if($input->GetTrade_type() == "NATIVE")
        {
            $result = \Wechat\WxPayApi::unifiedOrder($input);
            return $result;
        }
    }

}
